package com.ruleengine.task.factory.impl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.ruleengine.parser.ITaskParser;
import com.ruleengine.parser.exception.RuleEngineParserException;
import com.ruleengine.task.config.TaskConfigManager;
import com.ruleengine.task.factory.IWorkflowFactory;
import com.ruleengine.task.impl.WorkflowTask;

public class DefaultWorkflowFactory implements IWorkflowFactory {
    private static Logger logger = Logger.getLogger(DefaultWorkflowFactory.class);
    
    /* (non-Javadoc)
     * @see com.wx.workflow.task.factory.IWorkflowFactory#createWorkflow(java.io.InputStream, java.lang.String)
     */
    public WorkflowTask createWorkflow(InputStream taskConfig,String codeing) throws RuleEngineParserException{
        // TODO Auto-generated method stub
        Document doc =null;
        SAXReader saxReader = null;
        try{
            //读取配置文件
             saxReader = new SAXReader(); 
             doc = saxReader.read(new InputStreamReader(taskConfig));
        }catch(Exception e){
            throw new RuleEngineParserException("the format of taskConfig is error",e);
        }
        
        //读取工作流配置根节点
        Element root = doc.getRootElement();
        ITaskParser parser = TaskConfigManager.getInstance().getTaskParser(root.getName());
        return (WorkflowTask)parser.parse(root);
    }
    
    /* (non-Javadoc)
     * @see com.wx.workflow.task.factory.IWorkflowFactory#createWorkflow(java.io.InputStream)
     */
    public WorkflowTask createWorkflow(InputStream taskConfig)
            throws RuleEngineParserException {
        // TODO Auto-generated method stub
        return createWorkflow(taskConfig,"utf8");
    }

    public static void main(String[] args){
        try{
            String f = "D:\\eclipse\\sgworkspance\\YBT_Simple\\conf\\adapter\\channel\\icbc.xml";
            WorkflowTask task = new DefaultWorkflowFactory().createWorkflow(new FileInputStream(f), "utf-8");
            logger.debug(task);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
